import { RouteRecordNormalized } from 'vue-router'
import { tagRouteConfig } from '@/layout/types'
import { useKeepAliveStoreWithOut } from '@/store/keepAlive/keepAliveStore'
const keepAliveStore = useKeepAliveStoreWithOut()

// 处理缓存路由（添加、删除、刷新）
export const handleAliveRoute = (matched: RouteRecordNormalized[], mode?: string) => {
  switch (mode) {
    case 'add':
      matched.forEach((v) => {
        keepAliveStore.keepAliveOperate({ mode: 'add', name: v.name })
      })
      break
    case 'delete':
      keepAliveStore.keepAliveOperate({ mode: 'delete', name: matched[matched.length - 1].name })
      break
    default:
      keepAliveStore.keepAliveOperate({ mode: 'delete', name: matched[matched.length - 1].name })
      setTimeout(() => {
        matched.forEach((v) => {
          keepAliveStore.keepAliveOperate({ mode: 'add', name: v.name })
        })
      }, 10)
  }
}

// 批量删除缓存路由(keepalive)
export const delAliveRoutes = (delAliveRouteList: Array<tagRouteConfig>, keepArr) => {
  delAliveRouteList.forEach((route) => {
    if (!keepArr.includes(route.name)) {
      keepAliveStore.keepAliveOperate({ mode: 'delete', name: route?.name })
    }
    keepAliveStore.removeScrollPosition(route?.path)
  })
}
